/**     
 * @{#} MCConfigure.java Create on 2011-7-21 下午10:16:11     
 *     
 * Copyright (c) 2011 by xiaofeng.zhouxf     
 */
package com.sefer.memcached.configure;

import java.util.LinkedList;

import com.sefer.memcached.command.Command;
import com.sefer.memcached.connect.ConnectResources;
import com.sefer.memcached.connectpool.ConnectPool;
import com.sefer.memcached.connectpool.DefaultConnectPoolImpl;
import com.sefer.memcached.constants.LifeEventInfo;
import com.sefer.memcached.exception.ClientException;
import com.sefer.memcached.lifecycle.CommandFireListenter;
import com.sefer.memcached.lifecycle.LifeCycle;
import com.sefer.memcached.lifecycle.LifeEvent;
import com.sefer.memcached.lifecycle.LifeListener;
import com.sefer.memcached.lifecycle.Listenerable;

/**
 * This class is used for initializate the connection.
 * 
 * @author <a href="mailto:xiaofeng.zhouxf83@gmail.com">xiaofeng.zhouxf</a>
 * @version 1.0
 */
public class MCConfigure implements LifeCycle, Listenerable {
	private ConnectPool pool;
	private ConnectResources resources;
	private LinkedList<LifeListener> queue = new LinkedList<LifeListener>();
	private String lifeCycleStats;

	@Override
	public boolean start() {
		if (LifeCycle.STATING == getState()) {
			pool = new DefaultConnectPoolImpl();
			CommandFireListenter commandFireListenter = new CommandFireListenter();
			commandFireListenter.setPool(pool);
			this.addListener(commandFireListenter);
			pool.initPool(resources);
			pool.setState(this.getState());
			return pool.start();
		}
		return false;
	}

	@Override
	public boolean stop() {
		return this.pool.stop();
	}

	@Override
	public String getState() {
		return this.lifeCycleStats;
	}

	public MCConfigure(ConnectResources resources) {
		super();
		this.resources = resources;
	}

	public void invokeCommand(Command command) throws ClientException {
		LifeEvent event = new LifeEvent(LifeEventInfo.CALL_SERVER, command);
		for (LifeListener lifeListener : queue) {
			lifeListener.fireEvent(event);
		}
	}

	@Override
	public void addListener(LifeListener listener) {
		if (listener != null) {
			// FIXME need delete the method of setPool and getPool from the
			// listener
			listener.setPool(pool);
			this.queue.add(listener);
		}
	}

	@Override
	public void setState(String state) {
		this.lifeCycleStats = state;
		if (pool != null)
			this.pool.setState(state);
	}
}
